package com.chen.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chen.entity.Employee;
import com.chen.entity.R;
import com.chen.exception.NameDuplicateException;
import com.chen.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Employee employee) {
//        log.info("PostMapping.login__________"+employee.toString());
        R login = employeeService.login(employee);
//        log.info("PostMapping.login__________"+login.toString());
        if (login.getCode() == 1) {
            Employee data = (Employee) login.getData();
            session.setAttribute("employee", data.getId());
        }
        return login;
    }

    @PostMapping("/logout")
    public R logout(HttpSession session) {
        session.invalidate();
        return R.success(null);
    }


    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        IPage<Employee> page1 = employeeService.page(page, pageSize, name);
        return R.success(page1);
    }


    //添加
    @PostMapping
    public R add(@RequestBody Employee employee, HttpSession session) {
        long employee1 = (long) session.getAttribute("employee");
        employee.setCreateUser(employee1);
        employee.setUpdateUser(employee1);
        employeeService.add(employee);
        return R.success("添加成功");
    }


    //查询一个
    @GetMapping("/{id}")
    public R findByid(@PathVariable Long id) {
        Employee employee = employeeService.findByid(id);
        return R.success(employee);
    }

    //修改
    @PutMapping
    public R update(@RequestBody Employee employee, HttpSession session) {
        long employee1 = (long) session.getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(employee1);
        try {
            employeeService.updateById(employee);
            return R.success(null);
        } catch (Exception e) {
            throw new NameDuplicateException();
        }
    }
}
